package com.mijie.homi.service.common;

import java.util.Date;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.mijie.homi.common.domain.user.DeviceInfo;
import com.mijie.homi.dao.commom.StatDao;
import com.mijie.homi.service.user.DeviceInfoService;
import com.mijie.util.HttpUtil;

@Service
public class StatService {

	@Autowired
	private StatDao dao;
	@Autowired
	private DeviceInfoService deviceInfoService;
	
	private Logger logger = Logger.getLogger(StatService.class);
	
	private boolean accept(String deviceId){
		DeviceInfo device = deviceInfoService.getDeviceInfo(deviceId);
		return device==null;
	}
	
	public int active(int channel,String deviceId){
		if(accept(deviceId)){
			return dao.incrActive(channel);
		}
		return 0;
	}
	
	public int prepareSignin(int channel,String deviceId){
		if(accept(deviceId)){
			return dao.incrPrepareSignin(channel);
		}
		return 0;
	}
	
	public int finishSignin(int channel,String deviceId){
		DeviceInfo device = deviceInfoService.getDeviceInfo(deviceId);
		boolean flag = false;
		if(device==null){
			flag = true;
		}else{
			Date now = new Date();
			if(now.getTime()-device.getCreateAt().getTime()<=5000)
				flag = true;
		}
		return flag?dao.incrFinishSignin(channel):0;
	}
	
	@Transactional(rollbackFor={Exception.class})
	public int finishSignup(int channel,String deviceId){
		return dao.incrFinishSignupByNormal(channel);
	}
	
	public int decrFinishSignupByNormal(int channel){
		return dao.decrFinishSignupByNormal(channel);
	}
	
	public int prepareSignup(int channel,String deviceId){
		if(accept(deviceId)){
			return dao.incrPrepareSignupByNormal(channel);
		}
		return 0;
	}
	
	public int prepareSignupUsingSinaWeibo(int channel,String deviceId){
		if(accept(deviceId)){
			return dao.incrPrepareSignupUsingSinaWeibo(channel);
		}
		return 0;
	}
	
	@Transactional(rollbackFor={Exception.class})
	public int finishSignupUsingSinaWeibo(int channel,String deviceId){
		return dao.incrFinishSignupUsingSinaWeibo(channel);
	}
	
	public int decrFinishSignupUsingSinaWeibo(int channel){
		return dao.decrFinishSignupUsingSinaWeibo(channel);
	}
	
	public int prepareSignupUsingQQWeibo(int channel,String deviceId){
		if(accept(deviceId)){
			return dao.incrPrepareSignupUsingQQWeibo(channel);
		}
		return 0;
	}
	
	@Transactional(rollbackFor={Exception.class})
	public int finishSignupUsingQQWeibo(int channel,String deviceId){
		return dao.incrFinishSignupUsingQQWeibo(channel);
	}
	
	public int decrFinishSignupUsingQQWeibo(int channel){
		return dao.decrFinishSignupUsingQQWeibo(channel);
	}
	
}
